import sys, os, xmpp, time
import datastore

class GtalkClient:
	def __init__(self, data):
		self.data = data
		jid = xmpp.protocol.JID(data.user)
		self.client = xmpp.Client(jid.getDomain(), debug=[])
		print "Connecting to %s:%s ... " %(data.server, data.port, )
		con = self.client.connect(server=(data.server, data.port))
		if not con:
				print "failed"
				sys.exit()
		print "done"
		print "Authenticating username %s ... " % (data.user, )
		auth = self.client.auth(jid.getNode(), data.password, 'Home')
		if not auth:
				print "failed"
				sys.exit()
		print "done"
		self.client.Dispatcher.RegisterHandler('message', self.msg_handler)
		self.client.sendInitPresence()

	def CheckAuthorization(self, fromJid):
		return self.data.IsJIDAllowed(fromJid)

	def msg_handler(self, con, event):
		print "here"
		fromJid = event.getFrom().getStripped()
		type = event.getType()
		msg = str(event.getBody()).lstrip().rstrip()
		print "Received: <%s> %s : %s" % (type, fromJid, msg)
		if not self.CheckAuthorization(fromJid):
			print "%s is not allowed to execute shell commands" % (str(fromJid))
			self.SendMessage(fromJid, "Sorry, you are not authorized to execute shell commands")
			return
		self.ProcessMessage(fromJid, msg)
	
	def FilterMessage(self, msg):
		__doc__="Check if the message should be allowed"
		return True # for now

	def ProcessMessage(self, fromJid, msg):
		if (msg == 'bye'):
			print "Exiting ..."
			self.online = False
			return
		result = os.popen(msg).read()
		print "Result:\n%s\n" % result
		self.SendMessage(fromJid, result)
		
	def SendMessage(self, toJid, msg):
		self.client.send(xmpp.protocol.Message(str(toJid), str(msg)))

	def Loop(self):
		self.online = True
		while (self.online):
				#print "sleeping for 1 sec"
				self.client.Process(1) # sleep for one second
		print "Finishing"
